package com.ayu.wxgzh.ayucyy.service;

import com.alibaba.fastjson.JSON;
import com.ayu.wxgzh.ayucyy.Utils.RecognizeCharacterUtil;
import com.ayu.wxgzh.ayucyy.Utils.WeChatUtil;
import com.ayu.wxgzh.ayucyy.chain.HandlerClient;
import com.ayu.wxgzh.ayucyy.chain.handler.AbstractHandler;
import com.ayu.wxgzh.ayucyy.entity.BaseMessage;
import com.ayu.wxgzh.ayucyy.entity.NewsMessage;
import com.ayu.wxgzh.ayucyy.entity.TextMessage;
import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * @Author 徐林玉
 * @Description MessageService
 * @Date 2022/8/29 16:51
 * @Version 1.0
 */
@Service
@Slf4j
public class MessageService {


    private static final String DEFAULT_CONTENT = "OpenAI正在努力运算中，请稍后使用相同的问题询问我，\n还可以使用draw关键字叫我生成图片哦~";


    private final HandlerClient handlerClient;

    private final EmojiService emojiService;

    @Autowired
    public MessageService(HandlerClient handlerClient, EmojiService emojiService) {

        this.handlerClient = handlerClient;
        this.emojiService = emojiService;
    }

    public String messageHandle(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 解析请求消息
            Map<String, String> requestMap = WeChatUtil.parseXml(request);
            log.info("接收到的消息内容：{}", JSON.toJSONString(requestMap));

            // 回复消息
            /*String responseXml = "<xml><ToUserName><![CDATA[" + requestMap.get("FromUserName") + "]]></ToUserName" +
                    "><FromUserName><![CDATA[" + requestMap.get("ToUserName") + "]]></FromUserName><CreateTime" +
                    ">12345678</CreateTime><MsgType><![CDATA[" + requestMap.get("MsgType") + "]]></MsgType><Content" +
                    "><![CDATA[最喜欢小猪猪了~]]></Content></xml>";*/
            String responseXml = replyMessage(requestMap);

            log.info("回复用户[{}]的消息内容：{}", requestMap.get("ToUserName"), responseXml);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(responseXml.getBytes());
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息处理异常：{}", e.getMessage());
        }
        return "OK";

    }


    // 处理回复消息
    private String replyMessage(Map<String, String> requestMap) {
        String respMsg = null;
        BaseMessage msg = null;
        String msgType = requestMap.get("MsgType");

        switch (msgType) {
            case "text":
                msg = dealTextMassage(requestMap);
                break;
            case "image":
                msg = dealImageMessage(requestMap);
                break;
            case "voice":
                break;
            case "video":
                break;
            case "shortvideo":
                break;
            case "location":
                break;
            case "link":
                break;
            default:
                msg = dealDefaultMsg(requestMap);
                break;
        }
        // 将消息对象转换成xml
        if (StringUtils.isNotBlank(msgType)) {
            respMsg = beanToXml(msg);
        }
        log.info("回复的消息内容：{}", respMsg);
        return respMsg;
    }

    /**
     * 将消息对象转换成xml
     *
     * @param msg
     * @return
     */
    private String beanToXml(BaseMessage msg) {
        XStream xStream = new XStream();
//        xStream.processAnnotations(new Class[]{TextMessage.class, ImageMessage.class, VoiceMessage.class, VideoMessage.class, MusicMessage.class, NewsMessage.class});
        xStream.processAnnotations(new Class[]{TextMessage.class, NewsMessage.class});
        String xml = xStream.toXML(msg);
        return xml;
    }

    /**
     * 处理文本类型消息内容
     *
     * @param requestMap requestMap
     * @return 消息内容
     */
    private BaseMessage dealTextMassage(Map<String, String> requestMap) {
        TextMessage textMessage = null;
        String content = requestMap.get("Content");
        try {
            AbstractHandler chainHandler = handlerClient.getChainHandler();
            BaseMessage baseMessage = chainHandler.handle(requestMap);
            if (Objects.nonNull(baseMessage)) {
                return baseMessage;
            }
            // 调用智能机器人，获取回复消息内容
            //机器人到期了
            //ChatResponse chatResponse = ChatBootUtil.chat(content);
            //String respMsg = chatResponse.getBody().getMessages().get(0).getText().getContent();
            //textMessage = new TextMessage(requestMap, respMsg);
            textMessage = new TextMessage(requestMap, DEFAULT_CONTENT);
        } catch (Exception e) {
            log.error("责任链异常，异常原因：{}", e.getMessage());
            e.printStackTrace();
        }
        return textMessage;

    }

    /**
     * 默认消息处理。
     *
     * @param requestMap
     * @return
     */
    private BaseMessage dealDefaultMsg(Map<String, String> requestMap) {

        return new TextMessage(requestMap, DEFAULT_CONTENT);

    }


    /**
     * 处理图片类型消息（图片识别）
     *
     * @param requestMap
     * @return
     */
    private BaseMessage dealImageMessage(Map<String, String> requestMap) {

        TextMessage textMessage = null;
        String picUrl = requestMap.get("PicUrl");
        String content = "";
        try {
            content = RecognizeCharacterUtil.RecognizeCharacter(picUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("图片识别异常：{}", e.getMessage());
        }
        textMessage = new TextMessage(requestMap, content);


//        String picUrl = requestMap.get("PicUrl");
//        String content = "表情处理完成：<a href=\""+picUrl+"\">点击下载</a>";
//        TextMessage textMessage = new TextMessage(requestMap, content);


        return textMessage;
    }


}
